package zookeeper

import (
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"strings"
	"time"
)

func must(err error) {
	if err != nil {
		panic(err)
	}
}

func Connect() *zk.Conn {
	servers := strings.Split("47.100.181.0:2181", ",")
	conn, _, err := zk.Connect(servers, time.Second)
	must(err)
	return conn
}

func Watch(conn *zk.Conn, path string) (chan []string, chan error) {
	snapshots := make(chan []string)
	errors := make(chan error)

	go func() {
		for {
			//watch
			snapshot, _, events, err := conn.ChildrenW(path)
			if err != nil {
				fmt.Printf("error  get node data %+v\n", err)
				errors <- err
				return
			}
			//fmt.Printf("get node data %+v\n", snapshot)
			snapshots <- snapshot
			evt := <-events
			if evt.Err != nil {
				fmt.Printf("error  get node data %+v\n", evt.Err)
				errors <- evt.Err
				return
			}
		}
	}()
	return snapshots, errors
}
